<template>
  <div class="main">
    <div class="header">
      <span class="title">统一认证中心</span>
    </div>
    <el-form class="user-layout-login" @keyup.enter="handleSubmit" autocomplete="off">
      <login-account ref="accLogin" :valid-code="false" :rules="rules"/>
      <el-form-item style="margin-top:24px">
        <el-button size="large" type="primary" htmlType="submit" class="login-button" :loading="loginBtn"
                   @click.stop.prevent="handleSubmit" :disabled="loginBtn">
          确定
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import {Md5} from 'ts-md5';
import {removeItem, setItem} from "@/utils/SystemUtil";
import LoginAccount from "@/views/login/LoginAccount.vue";

import {CACHE_INCLUDED_ROUTES} from "@/stores/conf";

import {getCurrentInstance, onMounted, reactive, ref, toRaw} from "vue";
import {useRouter} from 'vue-router'
import {useStore} from "@/stores";
import {msgWarn} from "@/utils/InfoUtil";
import {userAuthorize} from "@/apis";
import {executeLoginByCode} from "@/utils/LoginUtil";

const router = useRouter();
const store = useStore();
const cache = getCurrentInstance()?.proxy?.$sessionCache;
const accLogin = ref();
const loginBtn = ref();

const rules = reactive({
  username: [{required: true, message: '请输入用户名称', trigger: ['blur', 'change']},],
  password: [{required: true, message: '请输入用户密码', trigger: ['blur', 'change']},],
  checkCode: [{required: true, message: '请输入验证码', trigger: ['blur', 'change']},],
})

onMounted(async () => {
  cache.remove(CACHE_INCLUDED_ROUTES);
});

const doLoginByCode = async (code: string) => {
  loginBtn.value = false;
  if (await executeLoginByCode(code, '/platform-list')) {
    loginBtn.value = true;
    const assets: any = store.getUserAssets();
    loginBtn.value = false;

    if (!assets || !assets.menus || assets.menus.length == 0) {
      msgWarn('用户无权访问')
      return;
    } else {
      await router.replace({
        path: store.getHomeRoute(),
        query: {}
      });
    }
  }
}

const handleLogin = async (params: any) => {
  const md5: any = new Md5();
  md5.appendAsciiStr(params.password)
  const password = md5.end()
  const authMode: string = import.meta.env.VITE_APP_LOGIN_MODE;
  const loginParam: any = store.getLoginParam();

  // 开始请求后端接口登录
  const loginContext: any = {
    category: 'account',
    authType: 'password',
    authData: '',
    authMode: loginParam.platform ? loginParam.authMode : authMode,
    username: params.username,
    account: params.username,
    authCode: password,
  }

  const result = await userAuthorize(loginContext, loginParam, {
    key: params.key, code: params.checkCode
  });

  if (result && result.code === 0) {
    removeItem('UNI_MASTER_SESSION_ID');
    setItem('UNI_MASTER_SESSION_ID', result.data.ssoToken);

    // 本身系统管理平台，直接登录即可
    if (!loginParam.platform) {
      const pos: number = result.data.redirectUri.indexOf('code=');
      await doLoginByCode(result.data.redirectUri.substring(pos + 5));
    } else {
      // 其他平台，重定向到指定地址（会根据code换取登录token）
      window.location.href = result.data.redirectUri;
    }
  } else {
    accLogin.value?.refreshCaptcha();
    msgWarn(result.message);
  }
}

const handleSubmit = async () => {
  const params = await accLogin.value?.loginParams();

  if (params) {
    await handleLogin(toRaw(params));
  }
}

</script>

<style lang="less" scoped>
.main {
  border-radius: 8px;
  background-color: rgba(255, 255, 255, 0.95);
  padding: 38px 60px 32px 60px;
  position: relative;
  left: 60%;
  background-color: #fff;
}

.header {
  color: #29a8f5;
  font-size: 32px;
  font-weight: bold;
  text-align: center;
  padding-bottom: 32px;
  // padding-top: 30px;
}

.user-layout-login {
  label {
    font-size: 14px;
  }

  .getCaptcha {
    display: block;
    width: 100%;
    height: 40px;
  }

  .forge-password {
    font-size: 14px;
  }

  button.login-button {
    padding: 0 15px;
    font-size: 16px;
    height: 40px;
    width: 100%;
  }

  .user-login-other {
    text-align: left;
    margin-top: 32px;
    line-height: 22px;

    .item-icon {
      font-size: 24px;
      color: rgba(0, 0, 0, 0.2);
      margin-left: 16px;
      vertical-align: middle;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: #003b7f;
      }
    }

    .register {
      float: right;
    }
  }

  .valid-error .ant-select-selection__placeholder {
    color: #f5222d;
  }

  .ant-btn-primary {
    background-color: #234DE3;
    border-color: #234DE3;
  }
}
</style>

